#encoding=utf-8
from __future__ import division

import time
import ujson

from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum

import websys.webconfig as webconfig
from websys.models import (
UserInfo,BannerInfo,TableInfo,GameInfo,Feedback,GameRecord,RoomInfo,WithholdInfo,UserExpand,UserConsumeRecord,
ServerInfo,AgentInfo,NewsInfo,SystemConfig,
)

import  websys.fun as fun
import  websys.ReturnCode as errcode
import record_redis
from websys import db_redis

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
                         #其它。。。。。。。。。。。。。
                       #战绩
                    url(r'^gamerecord', 'websys.view.mjhall_jn.user_jn_gamerecord', name='jn_gamerecord'),
                       #录像列表
                       url(r'^videolist', 'websys.view.mjhall_jn.user_jn_videolist', name='jn_videolist'),
                       #录像详情
                       url(r'^videodetail', 'websys.view.mjhall_jn.user_jn_videodetail', name='jn_videodetail'),
                       #消息中心
                       url(r'^newslist', 'websys.view.mjhall_jn.user_jn_newslist', name='jn_newslist'),
                       #绑定代理id
                       url(r'^bindagent', 'websys.view.mjhall_jn.user_jn_bindagent', name='jn_bindagent'),
                       #跑马灯
                       url(r'^scrollnews', 'websys.view.mjhall_jn.user_jn_scrollnews', name='jn_scrollnews'),
    )


#########################################其它接口########################山东麻将的##################################################

#战绩
# http://127.0.0.1:8080/api/hall/jn/gamerecord?uid=1&gameid=1
#uid玩家帐号,游戏id
#{"msg":"","code":0,'data':{'allscore':100,'list':[
# {'roomid':'123123','time':123123123,'round':1,'user':[{'name':'我','uid':123,'score':5},{'name':'你','uid':234,'score':10}，{'name':'他','uid':823,'score':-5}，{'name':'他的','uid':573,'score':-10}]}
#.............
# ]}allscore总积分，list为记录列表,roomid房间号，time时间截，round局号，user为玩家列表，name名称，uid编号，score分数
def user_jn_gamerecord(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','gameid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
        t_gid = int(t_obj['gameid'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    def get_user_arr(use_obj,t_uid):
        user_ids=use_obj.keys()
        user_ids.sort()

        tmp_arr=[]
        if t_uid in use_obj:#自己的排第1
            my_data=use_obj[t_uid]
            tmp_arr.append(my_data)
        for ii_uid in user_ids:
            if ii_uid==t_uid:
                continue
            tmp_arr.append(use_obj[ii_uid])
        return tmp_arr

    t_time=time.time()
    t_list=[]
    date_from=fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY)
    #总积分，局数
    cur_obj=GameRecord.objects.filter(uid_id=t_uid,gameid_id=t_gid,start_time__gte=date_from).aggregate(score=Sum("score"),num=Count("id"))
    all_score=cur_obj["score"] or 0
    #参加的
    wh_info=WithholdInfo.objects.filter(uid_id=t_uid,create_time__gte=date_from).order_by('-id')
    #print(wh_info,'--t_time--111---',time.time()-t_time)
    for jj in wh_info:#每个房间
        cur_info=jj.tableid#房间对象
        if(t_gid>0) and (t_gid!=cur_info.gameid_id):#某个游戏
            continue
        #4个人的数据select uid_id,nickname,roundid,sum(score) as score from gamerecord where gameid=xxx and roomid=xxxx and recordid=xxx group by uid_id,nickname,roundid
        #cur_arr=GameRecord.objects.filter(gameid_id=cur_info.gameid_id,roomid=cur_info.roomid,recordid=cur_info.recordid).values('uid_id','nickname','roundid').annotate(score=Sum('score'))
        cur_arr=GameRecord.objects.filter(gameid_id=cur_info.gameid_id,roomid=cur_info.roomid,recordid=cur_info.recordid).order_by('-roundid')
        #redis读取
        #cur_obj=record_redis.GetUserTableRecord(t_uid,cur_info.gameid_id,cur_info.roomid)

        #print cur_info.recordid,'....000000.....',cur_arr,len(t_list)
        old_round=None
        if len(cur_arr)>0:
            use_obj={}
            for ii_item in cur_arr:
                tmp_round=ii_item.roundid
                cur_round=ii_item.recordid+'_'+str(tmp_round)

                if not old_round:
                    old_round=cur_round
                else:
                    if cur_round!=old_round:#新一局

                        # user_ids=use_obj.keys()
                        # user_ids.sort()
                        #
                        # my_data=use_obj[t_uid]
                        # tmp_arr=[my_data]
                        # for ii_uid in user_ids:
                        #     if ii_uid==t_uid:
                        #         continue
                        #     tmp_arr.append(use_obj[ii_uid])
                        tmp_obj['user']=get_user_arr(use_obj,t_uid)
                        t_list.append(tmp_obj)
                        #重置
                        old_round=cur_round
                        use_obj={}

                use_obj[ii_item.uid_id]={'uid':ii_item.uid_id,'name':ii_item.nickname,'score':ii_item.score}
                tmp_obj={"roomid":cur_info.roomid,"time":fun.DateTimeToTimetuple(ii_item.start_time),"round":tmp_round}

            tmp_obj['user']=get_user_arr(use_obj,t_uid)
            t_list.append(tmp_obj)

    t_res['code']=0
    t_res['data']={'allscore':all_score,'list':t_list}

    return HttpResponse(ujson.dumps(t_res))

#录像列表
# http://127.0.0.1:8080/api/hall/jn/videolist?uid=1&gameid=1
#uid玩家帐号,游戏id
#{"msg":"","code":0,'data':[
# {'id':'12312312222','roomid':'123123','time':123123123,'round':1,'user':[{'name':'我','uid':123,'score':5},{'name':'你','uid':234,'score':10}，{'name':'他','uid':823,'score':-5}，{'name':'他的','uid':573,'score':-10}]}
#    ............
# ]}id记录id查牌展开参数,roomid房间号，time时间截，round局号，user为玩家列表，name名称，uid编号，score分数
def user_jn_videolist(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','gameid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
        t_gid = int(t_obj['gameid'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    def get_user_arr(use_obj,t_uid):
        user_ids=use_obj.keys()
        user_ids.sort()

        my_data=use_obj[t_uid]
        tmp_arr=[my_data]
        for ii_uid in user_ids:
            if ii_uid==t_uid:
                continue
            tmp_arr.append(use_obj[ii_uid])
        return tmp_arr

    t_time=time.time()
    t_list=[]
    date_from=fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY)
    #参加的
    wh_info=WithholdInfo.objects.filter(uid_id=t_uid,create_time__gte=date_from).order_by('-id')
    #print(wh_info,'--t_time--111---',time.time()-t_time)
    for jj in wh_info:#每个房间
        cur_info=jj.tableid#房间对象
        if(t_gid>0) and (t_gid!=cur_info.gameid_id):#某个游戏
            continue
        #4个人的数据select uid_id,nickname,roundid,sum(score) as score from gamerecord where gameid=xxx and roomid=xxxx and recordid=xxx group by uid_id,nickname,roundid
        cur_arr=GameRecord.objects.filter(gameid_id=cur_info.gameid_id,roomid=cur_info.roomid,recordid=cur_info.recordid).values('uid_id','nickname').annotate(score=Sum('score'),gtime=Max('start_time'))
        #cur_arr=GameRecord.objects.filter(gameid_id=cur_info.gameid_id,roomid=cur_info.roomid,recordid=cur_info.recordid).order_by('-roundid')
        #redis读取
        #cur_obj=record_redis.GetUserTableRecord(t_uid,cur_info.gameid_id,cur_info.roomid)

        #print cur_info.recordid,'....000000.....',cur_arr,len(t_list)
        old_round=None
        if len(cur_arr)>0:
            tmp_arr=[]
            for ii_item in cur_arr:
                tmp_arr.append({'uid':ii_item['uid_id'],'name':ii_item['nickname'],'score':ii_item['score']})

            tmp_obj={"id":cur_info.recordid,"roomid":cur_info.roomid,"time":fun.DateTimeToTimetuple(ii_item['gtime']),"round":cur_info.round}

            tmp_obj['user']=tmp_arr
            t_list.append(tmp_obj)

    t_res['code']=0
    t_res['data']=t_list

    return HttpResponse(ujson.dumps(t_res))

#录像详情
# http://127.0.0.1:8080/api/hall/jn/videodetail?uid=1&gameid=1&id=123131
#uid玩家帐号,游戏id
#{"msg":"","code":0,'data':[
# {'id':'12312312222','roomid':'123123','time':123123123,'round':1,'user':'我:5,你:234,他:-5,他的:-10}}
#    ............
# ]}id录像id回放参数,roomid房间号，time时间截，round局号，user为玩家列表
def user_jn_videodetail(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','gameid','id']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
        t_gid = int(t_obj['gameid'])
        t_recordid = t_obj['id']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    def get_user_arr(use_obj,t_uid):
        user_ids=use_obj.keys()
        user_ids.sort()

        tmp_str=''
        my_data=use_obj[t_uid]
        tmp_arr=[my_data]
        tmp_str='%s:%s'%(my_data['name'],my_data['score'])
        for ii_uid in user_ids:
            if ii_uid==t_uid:
                continue
            tmp_arr.append(use_obj[ii_uid])
            tmp_str+='   %s:%s'%(my_data['name'],my_data['score'])
        return tmp_str

    t_time=time.time()
    t_list=[]
    cur_arr=GameRecord.objects.filter(gameid_id=t_gid,recordid=t_recordid).order_by('-roundid')
        #redis读取
        #cur_obj=record_redis.GetUserTableRecord(t_uid,cur_info.gameid_id,cur_info.roomid)

    #print '....000000.....',cur_arr,len(t_list)
    old_round=None
    if len(cur_arr)>0:
        use_obj={}
        for ii_item in cur_arr:
            tmp_round=ii_item.roundid
            cur_round=ii_item.recordid+'_'+str(tmp_round)

            if not old_round:
                old_round=cur_round
            else:
                if cur_round!=old_round:#新一局
                    tmp_obj['user']=get_user_arr(use_obj,t_uid)
                    t_list.append(tmp_obj)
                    #重置
                    old_round=cur_round
                    use_obj={}

            use_obj[ii_item.uid_id]={'uid':ii_item.uid_id,'name':ii_item.nickname,'score':ii_item.score}
            tmp_obj={"roomid":ii_item.roomid,"time":fun.DateTimeToTimetuple(ii_item.start_time),"round":tmp_round}

        tmp_obj['user']=get_user_arr(use_obj,t_uid)
        t_list.append(tmp_obj)

    t_res['code']=0
    t_res['data']=t_list

    return HttpResponse(ujson.dumps(t_res))

#消息中心
# http://127.0.0.1:8080/api/hall/jn/newslist?uid=1
#uid玩家帐号
#{"msg":"","code":0,'data':[
# {'title':'12312312222','content':'123123','time':123123123}
#    ............
# ]}title标题，time时间截，content为详情
def user_jn_newslist(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))


    t_time=time.time()
    t_list=[]
    cur_arr=NewsInfo.objects.filter().order_by('-id')
        #redis读取
        #cur_obj=record_redis.GetUserTableRecord(t_uid,cur_info.gameid_id,cur_info.roomid)

    #print time.time()-t_time,'....000000.....',cur_arr,len(t_list)
    for ii_item in cur_arr:
        tmp_obj={"title":ii_item.title,"time":fun.DateTimeToTimetuple(ii_item.create_time),"content":ii_item.content}

        t_list.append(tmp_obj)

    t_res['code']=0
    t_res['data']=t_list

    return HttpResponse(ujson.dumps(t_res))

#绑定代理
# http://127.0.0.1:8080/api/hall/jn/bindagent?uid=1&agent_id=1
#uid玩家帐号,agent_id代理编号
#{"msg":"","code":0,'data':}
def user_jn_bindagent(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','agent_id']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
        t_agentid = int(t_obj['agent_id'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    u_info=UserInfo.objects.get(pk=t_uid)
    if u_info.agentid_id:
        t_res['msg']='agent exists'
        t_res['code']=errcode.DB_DataExists
        return HttpResponse(ujson.dumps(t_res))

    #if not AgentInfo.objects.filter(pk=t_agentid).exists():
    if not AgentInfo.objects.filter(bindcode=t_agentid).exists():
        t_res['msg']='error agentid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    #u_info.agentid_id=t_agentid
    ag_info=AgentInfo.objects.get(bindcode=t_agentid)
    u_info.agentid=ag_info
    u_info.save()

    t_res['code']=0

    return HttpResponse(ujson.dumps(t_res))

#滚动跑马灯
# http://127.0.0.1:8080/api/hall/jn/scrollnews?uid=1
#uid玩家帐号
#{"msg":"","code":0,'data': {'title':'12312312222','content':'123123','time':123123123}
#}title标题，time时间截，content为详情
def user_jn_scrollnews(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = int(t_obj['uid'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    t_typeid='scrollnews'
    t_time=time.time()
    tmp_obj={"title":t_typeid,"time":t_time,"content":u'[系统]欢迎来到游戏世界，快快加入，一起伤害。。。。。'}
    sc_arr=SystemConfig.objects.filter(typeid=t_typeid).values('content')
    if sc_arr:
        tmp_obj['content']=sc_arr[0]['content']

    t_res['code']=0
    t_res['data']=tmp_obj

    return HttpResponse(ujson.dumps(t_res))